package my.yuan.fkzapp.controller.demo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import my.yuan.fkzapp.response.CommonResult;
import my.yuan.fkzapp.validator.DemoValidator;
import my.yuan.fkzapp.vo.DemoVO;
import my.yuan.fkzcommon.exception.InputParamException;
import my.yuan.fkzmapper.ddo.DemoDO;
import my.yuan.fkzmapper.ddo.DemoSlaveDO;
import my.yuan.fkzmapper.mapper.master.DemoMapper;
import my.yuan.fkzmapper.mapper.slave.DemoSlaveMapper;
import org.hibernate.validator.constraints.Length;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @author qy
 * @description z
 * @date 2021-10-01
 */
@Api(tags = "Test模块")
@RequestMapping("/test")
@RestController
@Slf4j
@CacheConfig(cacheNames = "TestController")
public class TestController {
    @Autowired
    private DemoValidator demoValidator;
    @Autowired
    private DemoMapper demoMapper;
    @Autowired
    private DemoSlaveMapper demoSlaveMapper;
    @Autowired
    private my.yuan.fkzredis.mapper.DemoMapper demoRedisMapper;

    @ApiOperation(value = "向客人问好")
    @GetMapping("/sayHi")
    public String sayHi(@RequestParam(value = "name") String name) {
        return "Hi " + name;
    }

    @ApiOperation(value = "demoVO")
    @GetMapping("/demoVO")
    public CommonResult<DemoVO> demoVO(@RequestBody @Valid DemoVO demoVO) {
        return CommonResult.success(demoVO);
    }

    @ApiOperation(value = "@Validated")

    @GetMapping("/validated")
    public CommonResult<String> validated(@Validated @Length(max = 3) String name) {
        log.info(name);
        return CommonResult.success(name);
    }


    @ApiOperation(value = "demoValidator")
    @GetMapping("/demoValidator")
    public CommonResult<DemoVO> demoValidator(@RequestBody DemoVO demoVO) {
        Errors errors = new BeanPropertyBindingResult(demoVO, "demoVO");
        demoValidator.validate(demoVO, errors);
        if (errors.hasErrors()) {
            throw new InputParamException("参数错误");
        }
        return CommonResult.success(demoVO);
    }

    @GetMapping("/masterDs")
    @Cacheable(key = "#root.methodName")
    public List<DemoDO> masterDs() throws InterruptedException {
        Thread.sleep(3000);
        return demoMapper.list();
    }

    @GetMapping("/slaveDs")
    public List<DemoSlaveDO> slaveDs() {
        return demoSlaveMapper.list();
    }

    @GetMapping("/redis/demoGet")
    public String demo(){
        return demoRedisMapper.get();
    }
}
